using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;


namespace MES
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        // Get a handle to an application window.
        [DllImport("USER32.DLL")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("USER32.DLL")]
        public static extern bool IsIconic(IntPtr hWnd);

        [DllImport("user32.dll")]      
        public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        // Activate an application window.
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        private const int SW_HIDE = 0;
        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMINIMIZED = 2;
        private const int SW_SHOWMAXIMIZED = 3;
        private const int SW_SHOWNOACTIVATE = 4;
        private const int SW_RESTORE = 9;
        private const int SW_SHOWDEFAULT = 10;


        [STAThread]
        static void Main()
        {            
            bool instanceCountOne = false;
            using (Mutex mutex = new Mutex(true,"MES",out instanceCountOne))
            {
                if(instanceCountOne)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new LoginForm());
                    mutex.ReleaseMutex();
                }
                else
                {
                    String proc = Process.GetCurrentProcess().ProcessName;
                    Process[] processes = Process.GetProcessesByName(proc);
                    if (processes.Length >= 1)
                    {
                        foreach (Process p in processes)
                        {
                            IntPtr point = p.MainWindowHandle;
                            if (IsIconic(point))
                            {
                                ShowWindowAsync(point, SW_RESTORE);
                            }
                            SetForegroundWindow(point); 
                        }                        
                        return;
                    }                   
                   
                }
            }
           
        }
    }
}